package com.chen10.gobang.common.exception;

import com.chen10.gobang.common.enums.response.ErrorEnum;
import com.chen10.gobang.common.protocal.ResponseVO;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理文件上传大小异常
     * @param exc
     * @return
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResponseEntity<ResponseVO<?>> handleMaxSizeException(MaxUploadSizeExceededException exc) {
        log.error("File size exceeds limit: {}", exc.getMessage());
        ResponseVO<?> responseVO = createResponseVO("error", HttpStatus.BAD_REQUEST.value(), ErrorEnum.FILE_SIZE_EXCEED_LIMIT.getMessage());
        return new ResponseEntity<>(responseVO, HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理MultipartException异常
     * @param exc
     * @return
     */
    @ExceptionHandler(MultipartException.class)
    public ResponseEntity<ResponseVO<?>> handleMultipartException(MultipartException exc) {
        log.error("MultipartException: {}", exc.getMessage());
        ResponseVO<?> responseVO = createResponseVO("error", HttpStatus.BAD_REQUEST.value(), ErrorEnum.MULTIPART_EXCEPTION.getMessage());
        return new ResponseEntity<>(responseVO, HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理JWT过期异常
     */
    @ExceptionHandler(ExpiredJwtException.class)
    public ResponseEntity<ResponseVO<?>> handleExpiredJwtException(ExpiredJwtException exc) {
        log.warn("Token has expired: {}", exc.getMessage());
        ResponseVO<?> responseVO = createResponseVO("error", HttpStatus.UNAUTHORIZED.value(), ErrorEnum.TOKEN_EXPIRED.getMessage());
        return new ResponseEntity<>(responseVO, HttpStatus.UNAUTHORIZED);
    }


    private ResponseVO<?> createResponseVO(String status, Integer code, String message) {
        ResponseVO<?> responseVO = new ResponseVO<>();
        responseVO.setStatus(status);
        responseVO.setCode(code);
        responseVO.setMessage(message);
        responseVO.setData(null);
        return responseVO;
    }
}
